//C++ : $Id$
/*
-----------------------------------------------------------------------
	XR Core
---------------

Copyright 2010 Daher Alfawares

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-----------------------------------------------------------------------
*/


#ifdef WIN32
#undef UNICODE
# include <shlwapi.h>
# include <shlobj.h>
#endif

#include <cstdlib>
#include <string>
#include <process.h>
#include <direct.h> // for getcwd


namespace xr { namespace core { namespace env
	{

	std::string get( std::string _Var )
		{
		const char *Value = std::getenv( _Var.c_str() );

		return Value ? Value : "";
		}

	std::string home()
		{
		std::string HomePath;
#ifdef WIN32
		HomePath += get( "HOMEDRIVE" );
		HomePath += get( "HOMEPATH" );
#else
		HomePath += get( "HOME" );
#endif
		return HomePath;
		}

	std::string tmp()
		{
		return get( "TMP" );
		}

	std::string os()
		{
		return get( "OS" );
		}

	std::string path()
		{
		return get( "PATH" );
		}

	void path( std::string _Path )
		{
		_putenv( (std::string("PATH=")+_Path).c_str() );
		}

	std::string cd()
		{
		char* Buffer;
		std::string Cd;

			// Get the current working directory: 
		Buffer = _getcwd( NULL, 0 );

		if( Buffer )
			{
			Cd = Buffer;
			free(Buffer);
			}

		return Cd;
		}

	void cd( std::string _Cd )
		{
#ifdef WIN32
		SetCurrentDirectory( _Cd.c_str() );
#endif
		}


	namespace application
		{

#ifdef WIN32

		std::string base()
			{
			char PathArray[MAX_PATH];
			GetModuleFileName( NULL, PathArray, MAX_PATH );
			
			std::string Path = PathArray;
			std::string::size_type t = Path.find_last_of("\\");

			return Path.substr(0,t);
			}

		std::string data()
			{
			char Path[MAX_PATH];
			LPITEMIDLIST ItemList;
			
			SHGetFolderLocation( 0, CSIDL_APPDATA, 0, 0, &ItemList );
			SHGetPathFromIDList( ItemList, Path );
			ILFree( ItemList );

			return std::string( Path );
			}

		std::string common_data()
			{
			char Path[MAX_PATH];
			LPITEMIDLIST ItemList;
			
			SHGetFolderLocation( 0, CSIDL_COMMON_APPDATA, 0, 0, &ItemList );
			SHGetPathFromIDList( ItemList, Path );
			ILFree( ItemList );

			return std::string( Path );
			}

#else
		
		std::string data()
			{
			return home();
			}

#	if defined MAC

		std::string base()
			{
			std::string path = "./";
			ProcessSerialNumber PSN;
			ProcessInfoRec pinfo;
			FSSpec pspec;
			FSRef fsr;
			OSStatus err;
			/* set up process serial number */
			PSN.highLongOfPSN = 0;
			PSN.lowLongOfPSN = kCurrentProcess;
			/* set up info block */
			pinfo.processInfoLength = sizeof(pinfo);
			pinfo.processName = NULL;
			pinfo.processAppSpec = &pspec;
			/* grab the vrefnum and directory */
			err = GetProcessInformation(&PSN, &pinfo);
			if (! err )
				{
				char c_path[2048];
				FSSpec fss2;
				int tocopy;
				err = FSMakeFSSpec(pspec.vRefNum, pspec.parID, 0, &fss2);
				if ( ! err )
					{
					err = FSpMakeFSRef(&fss2, &fsr);
					if ( ! err )
						{
						char c_path[2049];
						err = (OSErr)FSRefMakePath(&fsr, (UInt8*)c_path, 2048);
						if (! err )
							{
							path = c_path;
							}
						}
					}
				}
        
			return (path);
			}

#	elif defined( LINUX )

		std::string base()
			{
			std::string Path;

			pid_t Pid = getpid();

			std::stringstream Link;
			Link << "/proc/" << Pid << "/exe";

			char proc[512];
			int ch = readlink(Link.str().c_str(),proc,512);
			if (ch != -1)
				{
				proc[ch] = 0;
				path = proc;
				std::string::size_type t = path.find_last_of("/");
				path = path.substr(0,t);
				}
			
			return path;
			}

#	endif
#endif

		} /* application */

	} /* env */ } /* core */ } /* xr */

